package com.learn.spring.dao;

import com.learn.spring.entity.TUser;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Repository
public class JdbcTemplateDao implements IJdbcTemplateDao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addUser(TUser user) {
        int update = jdbcTemplate.update("insert into t_user(name, password, sex, age) values(?,?,?,?)", user.getName(), user.getPassword(), user.getSex(), user.getAge());
        System.out.println("插入了"+update+"行");
    }

    @Override
    public void updateUser(TUser user) {
        int update = jdbcTemplate.update("update t_user set name=?, password=?, sex=?, age=? where id = ?",
                user.getName(), user.getPassword(), user.getSex(), user.getAge(), user.getId());
        System.out.println("更新了"+update+"行");
    }

    @Override
    public void deleteUser(int id) {
        int update = jdbcTemplate.update("delete from t_user where id = ?", id);
        System.out.println("删除了"+update+"行");
    }

    @Override
    public int selectCount() {
        return jdbcTemplate.queryForObject("select count(*) from t_user", Integer.class);
    }

    @Override
    public TUser findUserById(int id) {
        return jdbcTemplate.queryForObject("select * from t_user where id=?", new BeanPropertyRowMapper<TUser>(TUser.class), id);
    }

    @Override
    public List<TUser> findAll() {
        return jdbcTemplate.query("select * from t_user", new BeanPropertyRowMapper<TUser>(TUser.class));
    }

    @Override
    public void batchAddUser(List<Object[]> list) {
        int[] update = jdbcTemplate.batchUpdate("insert into t_user(name, password, sex, age) values(?,?,?,?)", list);
        System.out.println("插入了"+ Arrays.toString(update) +"行");
    }

    @Override
    public void batchUpdateUser(List<Object[]> list) {
        int[] update = jdbcTemplate.batchUpdate("update t_user set name=?, password=?, sex=?, age=? where id = ?", list);
        System.out.println("更新了"+ Arrays.toString(update) +"行");
    }

    @Override
    public void batchDeleteUser(List<Object[]> list) {
        int[] update = jdbcTemplate.batchUpdate("delete from t_user where id = ?", list);
        System.out.println("删除了"+ Arrays.toString(update) +"行");
    }
}
